const { err } = require("../error/base64");

let { HttpRequest, globalData, mfutil, UserAccess, addUserStat, URLChangeCommon } = getApp();
const app = getApp();


Page({
  data: {
    tilesDetail: {  // 详情数据
      tile_info: ''
    },
    urlImg: null,
    router: '/pages/wallpaper_page/wallpaper_page',
  },
  onLoad(options) {
    my.hideShareMenu({
      success() {
      },
      fail() {
      },
    });
    console.log(options, "opentions---------------------------------------------");
    let { id, lucky_image, lucky_text, prize_name, prize_sku, cta, urls } = options;

    this.setData({
      id, lucky_image, lucky_text, prize_name, prize_sku, cta: JSON.parse(cta), urls: JSON.parse(urls)
    })
    console.log(urls, '122434');
    this.setData({
      loadingActive: false
    })
    console.log(options, "qqqqqqqqqqqqqqqqqqqqqsss");
    this.initPage()


    /**
* 用户行为记录埋点
*/
    let routerArr = getCurrentPages();
    let params = app.globalData.params;
    let channel = app.globalData.channel;
    let UserAccessoptions = {
      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
      name: routerArr[routerArr.length - 1].data.pagetitle,
      address: options.id,
    }
    let track = UserAccess(UserAccessoptions)
    // 自定义埋点  
    let customAccessoptions = {
      customType: 'TileCover_' + options.id,
      // tileId: options.id
    }
    console.log(options.id, '进入奖品结束页');
    let tracks = addUserStat(customAccessoptions)
  },

  // 初始化数据
  async initPage() {
    console.log("11113434");
    let { tilesDetail, id, urls } = this.data;
  

    console.log(urls, "4444444444urls4");
    let isGif = false;
    urls.forEach(item => {

      if (item.indexOf('.gif') != -1) {
        isGif = true;
      }
      this.setData({
        isGif: isGif
      })
    });
    console.log("isGif::::" + isGif)
    let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/get?url=/v2/cms/api/tile/${id}`;
    let parmasObj = {
      member_id_type: 1,
      member_id: globalData.userInfo.memberId
    }
    this.setData({
      loadingActive: false
    })
    let res = await HttpRequest(path, 'POST', parmasObj, {});
    this.data.tilesDetail = res.data.data;

  },

  // 图片下载
  async copyLink() {
    const authorize = await this.Svaeimages_authorize();  // 获取本地相册
    if (!authorize) {
      my.openSetting();
      return;
    }

    let { urls } = this.data;
    let path1 = `/vans-family/api/v2.1/oss/aliyun/taobao/miniapp/uploadByUrls/vans`
    let body = {
      urls: urls
    }
    let res2 = await HttpRequest(path1, 'POST', {}, body);
    console.log(res2.data, "33333333prize_one_gift_urlprize_one_gift_urlprize_one_gift_url333333333333");
    this.data.urlImg = res2.data
    console.log(this.data.urlImg, '000000000000000000000000');
    let { urlImg } = this.data

    // 非空判断
    if (urlImg && urlImg.length > 0) {
      let urlImg1 = urlImg.find((item) => item.includes("gif"));

      if (urlImg1) {
        let arr = urlImg.map(item => {
          console.log(item, "111111");
          return item.replace('http://vansfamily.oss-cn-zhangjiakou.aliyuncs.com/image/', '')
        })

        console.log(encodeURIComponent(arr.toString()), "ppppppppppppppp");
        my.setClipboard({
          text: 'https://miniapp.vans-customs.cn/clm/index.html?str=' + encodeURIComponent(arr.toString()),
          success: (res) => {
            my.showToast({
              type: 'success',
              content: '链接复制成功,请前往浏览器下载',
              duration: 1500,
            });
          }
        });
      } else {
        urlImg.forEach(async (item, index) => {
          console.log(item, '@@@@@');
          let saveImges_res = await this.saveimges(item);
          console.log(saveImges_res, '@@@@@@@');
          if (saveImges_res == 0) {
            my.alert({
              title: '下载失败',
            })
            return;
          }
        });
        my.showLoading({
          content: "保存中..."
        });
        setTimeout(() => {
          my.alert({
            title: '下载成功!',
          })
          my.hideLoading();
        }, 1500);

      }

    }



  },


  // async copyLink() {
  //   const authorize = await this.Svaeimages_authorize();  // 获取本地相册
  //   if (!authorize) {
  //     my.openSetting();
  //     return;
  //   }

  //   let { urls } = this.data;
  //   let path1 = `/vans-family/api/v2.1/oss/aliyun/taobao/miniapp/uploadByUrls/vans`
  //   let body = {
  //     urls: urls
  //   }
  //   let res2 = await HttpRequest(path1, 'POST', {}, body);
  //   console.log(res2.data, "33333333prize_one_gift_urlprize_one_gift_urlprize_one_gift_url333333333333");
  //   this.data.urlImg = res2.data
  //   console.log(this.data.urlImg, '000000000000000000000000');
  //   let { urlImg } = this.data
  //   let num = 0

  //   urlImg.forEach(async (item, index) => {
  //     console.log(item, '@@@@@');
  //     let saveImges_res = await this.saveimges(item);
  //     console.log(saveImges_res, '@@@@@@@');
  //     if (saveImges_res == 0) {
  //       my.alert({
  //         title: '下载失败',
  //       })
  //       return;
  //     }
  //   });

  //   my.showLoading({
  //     content: "保存中..."
  //   });
  //   setTimeout(() => {
  //     my.alert({
  //       title: '下载成功!',
  //     })
  //     my.hideLoading();
  //   }, 1500);
  // },
  //授权本地相册
  async Svaeimages_authorize() {
    return new Promise((reslove, reject) => {
      // 发起用户授权
      my.authorize({
        scopes: 'scope.album',  //获取本地相册
        success: (res) => {
          reslove(1)
        },
        fail: (res) => {
          reslove(0);
        }
      })
    })
  },
  // 保存图片
  async saveimges(url) {
    return new Promise((resolve, reject) => {
      //保存在线图片到相册
      my.saveImage({
        url: url,
        showActionSheet: true,
        success: (res) => {
          console.log("=======下载中=======");
          resolve(1)
        },
        fail: (error) => {
          my.alert({
            content: JSON.stringify(error)
          })
          reject(0)
        }
      })
    })
  },
  // btn 链接跳转
  urlChange(event) {


    let { item } = event.currentTarget.dataset;
    console.log(item);

    URLChangeCommon(item)
    /**
    * 用户行为记录埋点
    */
    let routerArr = getCurrentPages();
    let params = app.globalData.params;
    let channel = app.globalData.channel;
    let UserAccessoptions = {
      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
      name: routerArr[routerArr.length - 1].data.pagetitle,
      address: this.data.id,
      String4: item.cta_button_name,

    }
    let track = UserAccess(UserAccessoptions)

    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileCTA_' + this.data.tilesDetail.tile_info.id + '_' + item.cta_button_name
      // tileId: this.data.tilesDetail.tile_info.id,
      // ctabtn: this.data.tilesDetail.tile_info.cta[0].cta_button_name
    }

    let tracks = addUserStat(customAccessoptions)
  },
})